package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.ApartmentInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;


    @Override
    public void customPageList(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customSelectPage(page,queryVo);
    }


    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;

    @Override
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        //判断是不是更新
       boolean isUpdate = apartmentSubmitVo.getId() != null;

       //解决不显示地区名称的问题,前端只传了id 没有传地名，fw前段
        //根据id查出地名
        //省
        ProvinceInfo provinceInfo = provinceInfoService.getById(apartmentSubmitVo.getProvinceId());
        //市
        CityInfo cityInfo = cityInfoService.getById(apartmentSubmitVo.getCityId());
        //区
        DistrictInfo districtInfo = districtInfoService.getById(apartmentSubmitVo.getDistrictId());

        //整进去
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());


       //调用方法保存或更新
        saveOrUpdate(apartmentSubmitVo);

        //更新之前先删除
        if (isUpdate){
            deleteSubTables(apartmentSubmitVo.getId());
        }

        //更新图片
        //从传来的apartmentSubmitVo中取出GraphVoList。
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)){
            //因为GraphInfo有四个属性，但是GraphVo只有两个，所以要补全再保存，差了所属对象的id和所属对象的类型。
            //创建一个GraphInfo的list，大小为graphVoList的大小。
            ArrayList<GraphInfo> graphInfoArrayList = new ArrayList<>(graphVoList.size());
            //赋值
            for (GraphVo graphVo : graphVoList) {
                //创建一个GraphInfo的对象
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                //加到数组
                graphInfoArrayList.add(graphInfo);
            }
            //调用图片的保存
            graphInfoService.saveBatch(graphInfoArrayList);
        }

        //更新配套
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            ArrayList<ApartmentFacility> apartmentFacilityArrayList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility =
                        ApartmentFacility.builder()
                                .apartmentId(apartmentSubmitVo.getId())
                                .facilityId(facilityInfoId)
                                .build();
                apartmentFacilityArrayList.add(apartmentFacility);
            }

            apartmentFacilityService.saveBatch(apartmentFacilityArrayList);
        }

        //跟新标签
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)){
            ArrayList<ApartmentLabel> apartmentLabelArrayList = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel =
                        ApartmentLabel.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId)
                        .build();

                apartmentLabelArrayList.add(apartmentLabel);
            }

            apartmentLabelService.saveBatch(apartmentLabelArrayList);
        }

        //更新杂费
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)){
            ArrayList<ApartmentFeeValue> apartmentFeeValueArrayList = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue =
                        ApartmentFeeValue.builder()
                                .apartmentId(apartmentSubmitVo.getId())
                                .feeValueId(feeValueId)
                                .build();

                apartmentFeeValueArrayList.add(apartmentFeeValue);
            }

            apartmentFeeValueService.saveBatch(apartmentFeeValueArrayList);
        }

    }

    @Override
    public ApartmentDetailVo customGetById(Long id) {
        ApartmentDetailVo apartmentDetailVo = apartmentInfoMapper.customSelectById(id);
        return apartmentDetailVo;
    }


    //根据ID删除公寓信息。
    @Autowired
    private RoomInfoService roomInfoService;
    /**
     * 思路：先判断要删除的公寓有没有核心子表，如果有就抛出异常，如果没有就删除表
     */
    @Override
    public void customRemoveById(Long id) {
        //判断公寓有没有核心子表（房间表）
        LambdaQueryWrapper<RoomInfo> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        //看放房间信息表中有没有对应id的公寓
        lambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(lambdaQueryWrapper);
        if (count>0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //如果没有子表就删除
        deleteSubTables(id);
        //删除公寓信息
        removeById(id);
    }



     //删除子表
    private void deleteSubTables(long apartmentId){
        //删除图片（根据所属对象类型，图片id）
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper
                =new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,apartmentId);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //删除配套信息
        LambdaQueryWrapper<ApartmentFacility> facilityLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        facilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentId);
        apartmentFacilityService.remove(facilityLambdaQueryWrapper);

        //删除标签关系
        LambdaQueryWrapper<ApartmentLabel> labelLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        labelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentId);
        apartmentLabelService.remove(labelLambdaQueryWrapper);

        //删除杂费
        LambdaQueryWrapper<ApartmentFeeValue> feeValueLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        feeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,apartmentId);
        apartmentFeeValueService.remove(feeValueLambdaQueryWrapper);
    }



}




